<script setup lang='ts'>
import type { VxeGridProps } from 'vxe-table'

import { useCfgAdd, useCfgDel, useGetCfgDict, useGetCfgPage } from '@fl/api/man-api/pricing-tool'
import { SearchForm, SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import { cloneDeep } from 'lodash-es'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'

import { initPage } from '../constant'
import CalcConfig from './calc-item-config.vue'

const router = useRouter()

const initState = { calcCategoryName: '' }
const state = ref(cloneDeep(initState))
const tablePage = ref(cloneDeep(initPage))

const addDiglog = ref(false)
const addForm = ref<any>(cloneDeep(initState))
const showCfg = ref(false)
const rowData = ref<any>({})

const params = computed(() => ({
    ...state.value,
    page: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
}))

const { data, isLoading, refetch } = useGetCfgPage(params)

const { data: opts } = useGetCfgDict()

const columns = [{
    colProps: {
        span: 6,
    },
    fieldProps: {
        filterable: true,
    },
    label: '计算项名称',
    options: computed(() => {
        let target = []
        if (opts.value?.length) {
            target = opts.value.map((v: any) => {
                return { label: v.name, value: v.name }
            })
        }
        return target
    }),
    prop: 'calcCategoryName',
    valueType: 'select',
}]

// 新增编辑
const addCol = [
    {
        fieldProps: {
            maxlength: 20,
        },
        label: '计算项名称',
        prop: 'calcCategoryName',
    },
]

const rules = {
    calcCategoryName: [{ message: '请输入计算项名称', required: true, trigger: 'blur' }],
}

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'calcCategoryName', title: '计算项名称' },
        { field: 'createTime', title: '创建日期' },
        { slots: { default: 'operate' }, title: '操作', width: 250 },
    ],
    height: 550,
    rowConfig: {
        keyField: 'calcCategoryId',
    },
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

function doAction(item: any, row: any) {
    switch (item.value) {
        case 'config':
            doCfg(row)
            break
        case 'view':
            router.push(`/operations-pages/pricing-tool/calc-detail` + `?calcCategoryId=${row.calcCategoryId}`)
            break
        case 'delete':
            doDel(row.calcCategoryId)
            break
        default:
            break
    }
}

function doCfg(row: any) {
    rowData.value = row
    showCfg.value = true
}

const { mutate } = useCfgDel()
function doDel(calcCategoryId: any) {
    mutate({ calcCategoryId }, {
        onSuccess: () => {
            afterSuccess()
        },
    })
}

function afterSuccess() {
    ElMessage({ message: '操作成功', type: 'success' })
    refetch()
}

function getData(val: any) {
    tablePage.value.currentPage = 1
    state.value = {
        ...state.value,
        ...val,
    }
}

function reset() {
    state.value = cloneDeep(initState)
    tablePage.value = cloneDeep(initPage)
}

const { mutate: mutateAdd } = useCfgAdd()
function doSave() {
    mutateAdd(addForm.value, {
        onSuccess: () => {
            addDiglog.value = false
            afterSuccess()
        },
    })
}

function goToList() {
    router.push('/operations-pages/pricing-tool/config-index')
}

function doShow() {
    addForm.value = cloneDeep(initState)
    addDiglog.value = true
}

function getBtns(val: any) {
    const btns = [
        {
            label: '配置',
            permission: [0, 1],
            text: true,
            value: 'config',
        },
        {
            label: '查看',
            permission: [1],
            text: true,
            value: 'view',
        },
        {
            label: '删除',
            permission: [0, 1],
            text: true,
            value: 'delete',
        },
    ]

    return btns.filter((v: any) => v.permission.includes(val))
}

watchEffect(() => {
    if (data.value) {
        tablePage.value.total = data.value.total
    }
})
</script>

<template>
    <el-button mb-20
               @click="goToList"
    >
        返回列表
    </el-button>

    <el-card class="mb-20">
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="查询"
                    class="mb-20"
                    @submit="getData"
                    @reset="reset"
        />
    </el-card>

    <el-card>
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     v-loading="isLoading"
                     :data="data?.records"
        >
            <template #toolbar_buttons>
                <el-button type="primary"
                           @click="doShow"
                >
                    + 新建
                </el-button>
            </template>

            <template #operate="{ row }">
                <div class="text-#dA0004 flex gap-15 justify-center">
                    <!-- 存在属性 可以查看 -->
                    <ButtonItem :btns="getBtns(row.hasProperty)"
                                @btn-click="doAction($event, row)"
                    />
                </div>
            </template>
        </SearchTable>
    </el-card>

    <!-- 新增弹框 -->
    <PlusDialogForm v-model:visible="addDiglog"
                    v-model="addForm"
                    title="新增"
                    width="500"
                    :form="{ columns: addCol, rules, labelWidth: 100 }"
                    @confirm="doSave"
    />

    <!-- 配置属性弹框 -->
    <CalcConfig v-if="showCfg"
                v-model="showCfg"
                :row="rowData"
    />
</template>
